import http from "../../utils/http";

Page({
  data: {
    formData: {
      cost_price: '',
      sales_price: '',
      profit: '0.00',
      now_date: ''
    },
    searchParams: {
      now_date: ''
    },
    priceList: [],
    filteredPriceList: [],
    currentPage: 1,
    totalPages: 1,
    isLoading: false
  },

  onLoad() {
    this.setData({
      'formData.now_date': this.getCurrentDate(),
      'searchParams.now_date': this.getCurrentDate()
    });
    this.getPriceList();
  },

  // 获取当前日期
  getCurrentDate() {
    const date = new Date();
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
  },

  // 输入框变化事件
  handleInputChange(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    
    this.setData({
      [`formData.${field}`]: value
    }, () => {
      if (field === 'cost_price' || field === 'sales_price') {
        this.calculateProfit();
      }
    });
  },

  // 计算利润
  calculateProfit() {
    const cost = parseFloat(this.data.formData.cost_price) || 0;
    const sales = parseFloat(this.data.formData.sales_price) || 0;
    const profit = (sales - cost).toFixed(2);
    this.setData({ 'formData.profit': profit });
  },

  // 日期选择
  bindDateChange(e) {
    this.setData({
      'formData.now_date': e.detail.value
    });
  },

  // 日期筛选变化事件
  bindSearchDateChange(e) {
    const date = e.detail.value;
    this.setData({ 'searchParams.now_date': date }, () => {
      this.setData({ currentPage: 1, priceList: [] }, () => {
        this.getPriceList();
      });
    });
  },

  // 获取价格列表
  getPriceList() {
    const page = this.data.currentPage;
    const date = this.data.searchParams.now_date;
    this.setData({ isLoading: true });

    http.request({
      url: apiConfig.getWheatPriceList+'?page=${page}&date=${date}',
      method: 'GET',
    }).then(res => {
      if (res.status === 200) {
        const newList = res.data;
        const allList = this.data.priceList.concat(newList);
        const filteredList = allList.filter(item => item.now_date === date); 
        this.setData({
          priceList: allList,
          filteredPriceList: filteredList,
          totalPages: res.totalPages,
          isLoading: false
        });
      }
    }).catch(err => {
      wx.showToast({ title: '获取数据失败', icon: 'none' });
      this.setData({ isLoading: false });
    });
  },

  // 滚动加载
  onReachBottom() {
    if (this.data.currentPage < this.data.totalPages) {
      this.setData({ currentPage: this.data.currentPage + 1 }, () => {
        this.getPriceList();
      });
    }
  },

  // 提交表单
  handleSubmit() {
    const params = {
      cost_price: this.data.formData.cost_price,
      sales_price: this.data.formData.sales_price,
      now_date: this.data.formData.now_date
    };

    http.request({
      url: apiConfig.addWheatPrice,
      method: 'POST',
      data: params,
    }).then(res => {
      if (res.status === 200) {
        if (res.status) {
          wx.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 2000,
            success: () => {
              // 刷新列表逻辑
              this.setData({ currentPage: 1, priceList: [] }, () => {
                this.getPriceList();
              });
            }
          });
        }
      }
    }).catch(err => {
      wx.showToast({ title: '提交失败', icon: 'none' }); 
    })
  }
})